/**
 * 打印机连接与打印功能模块
 */
export class PrinterService {
    private printWindow: Window | null = null;
  
    /**
     * 打印指定DOM元素内容
     * @param elementId 要打印的DOM元素ID
     * @param options 打印选项
     */
    public printElement(elementId: string, options?: PrintOptions): void {
      const element = document.getElementById(elementId);
      if (!element) {
        console.error(`Element with id '${elementId}' not found.`);
        return;
      }
  
      this.printWindow = window.open('', '_blank');
      if (!this.printWindow) {
        console.error('Failed to open print window.');
        return;
      }
  
      // 准备打印内容
      const printContent = element.outerHTML;
      const styles = this.getDocumentStyles();
  
      // 创建打印页面
      this.printWindow.document.write(`
        <html>
          <head>
            <title>${options?.title || '打印内容'}</title>
            ${styles}
            <style>
              @media print {
                body * {
                  visibility: hidden;
                }
                #print-content * {
                  visibility: visible;
                }
                #print-content {
                  position: absolute;
                  left: 0;
                  top: 0;
                  margin: 0;
                  padding: 15px;
                  width: 100%;
                }
              }
            </style>
          </head>
          <body>
            <div id="print-content">${printContent}</div>
            <script>
              window.onload = function() {
                window.print();
                setTimeout(function() {
                  window.close();
                }, 100);
              };
            </script>
          </body>
        </html>
      `);
  
      this.printWindow.document.close();
    }
  
    /**
     * 获取当前文档的样式
     */
    private getDocumentStyles(): string {
      const styles = [];
      const documentStyles = document.styleSheets;
      
      for (let i = 0; i < documentStyles.length; i++) {
        const styleSheet = documentStyles[i] as any;
        try {
          if (styleSheet.cssRules) {
            for (let j = 0; j < styleSheet.cssRules.length; j++) {
              styles.push(styleSheet.cssRules[j].cssText);
            }
          }
        } catch (e) {
          // 处理跨域样式表访问限制
          if (styleSheet.href) {
            styles.push(`@import url('${styleSheet.href}');`);
          }
        }
      }
      
      return `<style>${styles.join('')}</style>`;
    }
  
    /**
     * 直接打印整个页面
     */
    public printPage(): void {
      window.print();
    }
  }
  
  /**
   * 打印选项接口
   */
  export interface PrintOptions {
    title?: string; // 打印页面标题
    // 可扩展更多选项，如打印机名称、边距等
  }  